﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace YueRu.Common
{

    #region 发送短信类
    /// <summary>
    /// 短信平台帮助类
    /// </summary>
    public class SmsUtil
    {
        #region 属性
        /// <summary>
        /// Appid
        /// </summary>
        public string Account { get; set; }
        /// <summary>
        /// 短信平台账号
        /// </summary>
        public string Username { get; set; }
        /// <summary>
        /// 短信平台密码
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// 请求地址
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 请求参数
        /// </summary>
        public IDictionary<string, string> Data { get; set; }
        /// <summary>
        /// 编码
        /// </summary>
        public Encoding Encode { get; set; }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public SmsUtil()
        {
            Encode = Encoding.UTF8;
        }
        #endregion

        #region 发送验证码
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <returns></returns>
        public SmsResult Post()
        {
            byte[] byteArray = Encode.GetBytes(GetPostData());
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(Url));
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            //接收返回信息：
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                try
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encode);
                    string html = reader.ReadToEnd();
                    //返回状态吗
                    int len1 = html.IndexOf("</code>");
                    int len2 = html.IndexOf("<code>");
                    string code = html.Substring((len2 + 6), (len1 - len2 - 6));
                    //返回流水号
                    int len5 = html.IndexOf("</smsid>");
                    int len6 = html.IndexOf("<smsid>");
                    string smsid = html.Substring((len6 + 7), (len5 - len6 - 7));
                    //返回描述
                    int len3 = html.IndexOf("</msg>");
                    int len4 = html.IndexOf("<msg>");
                    string msg = html.Substring((len4 + 5), (len3 - len4 - 5));
                    SmsResult result;
                    if (code == "2")
                    {
                        result = new SmsResult(2, "短信发送成功");
                        result.SmsId = smsid;
                        return result;
                    }
                    else
                    {
                        result = new SmsResult(int.Parse(code), msg);
                        result.SmsId = smsid;
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    return new SmsResult(99, "异常:" + ex.ToString());
                }
            }
            else
            {
                return new SmsResult(11, "http请求错误:" + response.StatusCode);
            }
        }
        #endregion

        #region 字段转换请求参数
        /// <summary>
        /// 字典转换请求参数
        /// </summary>
        /// <returns>name1=value1&name2=value2</returns>
        private string GetPostData()
        {
            string postData = null;
            // 将数据项转变成 name1=value1&name2=value2 的形式
            if (Data != null && Data.Count > 0)
            {
                postData = string.Join("&",
                    (from kvp in Data
                     let item = kvp.Key + "=" + HttpUtility.UrlEncode(kvp.Value)
                     select item
                        ).ToArray()
                    );
            }
            return postData;
        }
        #endregion

        #region 获取时间戳
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public long GetTs(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return (time.Ticks - startTime.Ticks) / 10000000;
        }
        #endregion
    }
    #endregion

    #region 短信实体类
    /// <summary>
    /// 返回实体类
    /// </summary>
    public partial class SmsResult
    {
        /// <summary>
        /// 结果
        /// </summary>
        /// <param name="code">状态吗</param>
        /// <param name="msg">消息</param>
        public SmsResult(int code, string msg)
        {
            Code = code;
            Msg = msg;
        }
        /// <summary>
        /// 返回状态码
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 返回消息
        /// </summary>
        public string Msg { get; set; }
        /// <summary>
        /// 流水号
        /// </summary>
        public string SmsId { get; set; }
    }
    #endregion
}
